<template>
  <ElDialog
    v-model="dialogVisible"
    :title="title"
    width="800"
    :before-close="handleClose"
  >
    <div class="searchTable">
      <ElRow class="search-color">
        <ElCol :span="18">
          <div class="flex">
            <div style="margin-right: 10px">
              <span class="search-text">航线名称：</span>
              <ElInput
                v-model="airlineName"
                style="width: 200px"
                placeholder="请输入航线名称"
                @input="spaceInput"
              />
            </div>
            <div class="flex">
              <span class="search-text">无人机型号：</span>
              <ElSelect
                v-model="modelId"
                style="width: 200px"
                placeholder="请选择无人机型号"
                @change="search()"
              >
                <ElOption
                  v-for="item in modelList"
                  :key="item.id"
                  :label="item.modelName"
                  :value="item.id"
                />
              </ElSelect>
            </div>
          </div>
        </ElCol>
        <ElCol :span="6" class="t-r">
          <ElButton class="b-r-4" type="primary" @click="debouncedSearch"
            >查询</ElButton
          >
          <ElButton @click="resetForm()">重置</ElButton>
        </ElCol>
      </ElRow>
    </div>
    <div class="tablePage">
      <div style="margin-bottom: 20px">
        <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
          <ElTable.TableColumn
            prop="airlineName"
            label="航线名称"
            align="center"
            show-overflow-tooltip
          />
          <ElTable.TableColumn
            prop="airlineType"
            label="航线类型"
            align="center"
          />
          <ElTable.TableColumn
            prop="modelName"
            label="无人机型号"
            align="center"
          />
          <ElTable.TableColumn
            prop="totalDistance"
            label="航线长度（m）"
            align="center"
          />
          <ElTable.TableColumn
            prop="executeTime"
            label="预计执行时间"
            align="center"
          />
          <ElTable.TableColumn fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                :disabled="isRowDisabled(scope.row)"
                @click="rowClick(scope.row)"
              >
                选择
              </el-button>
            </template>
          </ElTable.TableColumn>
        </ElTable>
      </div>
    </div>
    <div class="pagination">
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">取消</ElButton>
        <ElButton type="primary" @click="submitForm()"> 确定 </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script lang="ts" setup>
import {
  ElDialog,
  ElButton,
  ElInput,
  ElMessage,
  ElTable,
  ElPagination,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
} from "element-plus";
import { reactive, ref, onMounted } from "vue";
import { list, getAllModel } from "#/api/task/airline";
import { useDebounceFn } from "@vueuse/core";

const emit = defineEmits(["airlineRow"]);
const dialogVisible = ref(false);
const title = ref("选择航线");
const airlineName = ref("");
const modelId = ref("");

const tableData = ref([]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);

const spaceInput = (value: string) => {
  // 过滤空格
  airlineName.value = value.replace(/\s+/g, "");
};

// 判断行是否应该禁用的函数
const isRowDisabled = (row) => {
  // 如果航线长度为null、undefined或0，则禁用选择按钮
  return row.totalDistance === null || 
         row.totalDistance === undefined || 
         row.totalDistance === 0 ||
         row.totalDistance === '';
};

const search = async () => {
  const params = {
    airlineName: airlineName.value,
    modelId: modelId.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  };
  try {
    const { data } = await list(params);
    if (data.records.length > 0) {
      tableData.value = data.records;
      total.value = data.total;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (err) {
    ElMessage.error("加载数据失败");
  }
};

const debouncedSearch = useDebounceFn(search, 500);

const addDialog = () => {
  dialogVisible.value = true;
  search();
};

const editDialog = (obj) => {
  dialogVisible.value = true;
  airlineName.value = obj.airlineName;
  search();
};

defineExpose({ addDialog, editDialog });

const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};

const submitForm = async (formEl) => {
  dialogVisible.value = false;
};

const resetForm = (formEl) => {
  airlineName.value = "";
  modelId.value = "";
  currentPage.value = 1;
  search();
};

const rowClick = (item) => {
  // 额外检查，防止通过键盘等方式触发被禁用的按钮
  if (isRowDisabled(item)) {
    ElMessage.warning("该航线长度无效，无法选择");
    return;
  }
  
  emit("airlineRow", item);
  dialogVisible.value = false;
};

const handleClose = () => {
  dialogVisible.value = false;
};

const modelList = ref([]);
const getAllModelList = async () => {
  const params = { modelName: "" };
  const { data } = await getAllModel(params);
  if (data.length > 0) {
    modelList.value = data;
  } else {
    modelList.value = [];
  }
};

onMounted(() => {
  getAllModelList();
});
</script>

<style lang="scss" scoped>
.tablePage {
  height: 50vh;
  margin-top: 20px;
  overflow-y: auto;
}

.tablePage::-webkit-scrollbar {
  width: 2px;
}

.flex {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
</style>